<?php
/**
 * Builds up a programmatic model for stacked SQL JOIN clauses to be used by SELECT query.
 * 
 * Note: MySQL uses join clause also for UPDATE, DELETE.
 */
class SQLJoinsClause extends AbstractSQLClause {
	protected $strLeftJoin = "LEFT OUTER JOIN";
	protected $strRightJoin = "RIGHT OUTER JOIN";
	protected $strInnerJoin = "INNER JOIN";
	
	public static function getInstance() {
		return new SQLJoinsClause();
	}
	
	/**
	 * Adds a left join clause
	 * 
	 * @example $mixTableName = "a" $objSQLCondition=new SQLCondition(array("b"=>"c"))
	 * @param SQLAliasClause|string $mixTableName
	 * @param SQLConditionsClause $objSQLCondition
	 * @return SQLJoinsClause
	 */
	public function addLeftJoin($mixTableName, $objSQLCondition) {
		$tblTMP = array();
		$tblTMP["TYPE"]=$this->strLeftJoin;
		$tblTMP["TABLE"]=(is_array($mixTableName)?new SQLAliasClause($mixTableName):$mixTableName);
		$tblTMP["CONDITION"]=$objSQLCondition;
		$this->tblContents[]=$tblTMP;
		return $this;
	}
	
	/**
	 * Adds a right join clause
	 *
	 * @example $mixTableName = new SQLAliasClause("d","x") $objSQLCondition=new SQLCondition(array("e"=>new SQLValue("f")))
	 * @param SQLAliasClause|string $mixTableName
	 * @param SQLConditionsClause $objSQLCondition
	 * @return SQLJoinsClause
	 */
	public function addRightJoin($mixTableName, $objSQLCondition) {
		$tblTMP = array();
		$tblTMP["TYPE"]=$this->strRightJoin;
		$tblTMP["TABLE"]=(is_array($mixTableName)?new SQLAliasClause($mixTableName):$mixTableName);
		$tblTMP["CONDITION"]=$objSQLCondition;
		$this->tblContents[]=$tblTMP;
		return $this;
	}
	
	/**
	 * Adds a inner join clause
	 *
	 * @example $mixTableName = "g" $objSQLCondition=new SQLCondition(array("h"=>"i"))
	 * @param SQLAliasClause|string $mixTableName
	 * @param SQLConditionsClause $objSQLCondition
	 * @return SQLJoinsClause
	 */
	public function addInnerJoin($mixTableName, $objSQLCondition) {
		$tblTMP = array();
		$tblTMP["TYPE"]=$this->strInnerJoin;
		$tblTMP["TABLE"]=(is_array($mixTableName)?new SQLAliasClause($mixTableName):$mixTableName);
		$tblTMP["CONDITION"]=$objSQLCondition;
		$this->tblContents[]=$tblTMP;
		return $this;
	}
	
	/**
	 * Transforms clause to string.
	 * 
	 * @example LEFT JOIN a ON b=c \r\n	RIGHT JOIN d AS x ON e='f' \r\n	INNER JOIN g ON h=i
	 * @see AbstractSQLClause::toString()
	 */
	public function toString() {
		$output="";
		foreach($this->tblContents as $tblTMP) {
			$output.=$tblTMP["TYPE"]." ".($tblTMP["TABLE"] instanceof SQLAliasClause?$tblTMP["TABLE"]->toString():$tblTMP["TABLE"])." ON ".$tblTMP["CONDITION"]->toString()."\r\n";
		}
		return $output;
	}
}